#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
网页版游戏控制器
处理游戏核心逻辑
"""

import random
from models.game_data import GameData
from models.player import Player

class WebGameController:
    """网页版游戏控制器"""
    
    def __init__(self):
        """初始化游戏控制器"""
        self.exams = GameData.EXAMS
        self.items = GameData.ITEMS
        self.events = GameData.EVENTS
        self.max_days = 7
        self.max_actions_per_day = 7  # 每天最多7次操作
    
    def start_new_game(self, teacher_type='kind'):
        """开始新游戏"""
        player = Player()
        game_state = {
            'day': 1,
            'game_over': False,
            'player': player.to_dict(),
            'actions_today': 0,  # 添加每日操作计数器
            'teacher_type': teacher_type,  # 添加老师类型
            'quiz_taken': False  # 添加随堂测试标记
        }
        return game_state
    
    def trigger_random_event(self):
        """触发随机事件"""
        for event in self.events:
            # 将事件概率调整为原来的60%
            if random.random() < event["probability"] * 0.6:
                return event
        return None
    
    def process_special_event(self, event_name, player):
        """处理特殊事件"""
        result = {
            "success": False,
            "message": "",
            "item": None
        }
        
        # 处理刷学长'真'题事件
        if event_name == "刷学长'真'题":
            # 扣除10点精力值
            player.energy = max(0, player.energy - 10)
            
            # 50%概率获得道具：前人智慧，50%概率被骗扣除10点知识值
            # 将概率调整为原来的60%
            if random.random() < 0.5 * 0.6:
                # 获得道具：前人智慧
                wisdom_item = {
                    "id": "wisdom",
                    "name": "前人智慧",
                    "effect": "exam",
                    "value": 20,
                    "description": "学长的智慧，考试分数加20"
                }
                result["item"] = wisdom_item
                result["success"] = True
                result["message"] = "你花了些精力研究学长的'真题'，获得了一个特殊道具：前人智慧！"
            else:
                # 被骗，扣除10点知识值
                player.knowledge = max(0, player.knowledge - 10)
                result["success"] = False
                result["message"] = "你花了精力研究学长的'真'题，结果发现是假的，不仅浪费了精力，还被误导损失了知识！"
        
        # 处理图书馆奇遇事件
        elif event_name == "图书馆奇遇":
            player.knowledge = player.knowledge + 10
            result["success"] = True
            result["message"] = "在图书馆遇到学霸，他愿意分享一些学习笔记，你的知识增加了10点！"
        
        # 处理室友的慷慨事件
        elif event_name == "室友的慷慨":
            player.health = min(100, player.health + 15)
            result["success"] = True
            result["message"] = "室友看你学习辛苦，给你买了夜宵，你的生命值增加了15点！"
        
        # 处理临时测验事件
        elif event_name == "临时测验":
            player.knowledge = max(0, player.knowledge - 10)
            result["success"] = False
            result["message"] = "老师突然宣布小测验，你没有准备，你的知识减少了10点！"
        
        # 处理网络崩溃事件（自动处理，不需要玩家选择）
        elif event_name == "网络崩溃":
            player.health = max(0, player.health - 10)
            result["success"] = False
            result["message"] = "选课系统崩溃，你无法选课，心情烦躁，你的生命值减少了10点！"
            result["auto_processed"] = True  # 标记为自动处理事件
            
        return result
    
    def find_random_item(self, player_inventory=None):
        """随机找到道具"""
        # 70%概率找到道具，调整为原来的60%
        if random.random() < 0.7 * 0.6:
            # 如果提供了玩家背包信息，则确保不重复获得相同物品
            if player_inventory is not None:
                # 获取玩家已有的物品ID列表
                existing_item_ids = [item["id"] for item in player_inventory]
                
                # 过滤出玩家还没有的物品
                available_items = [item for item in self.items if item["id"] not in existing_item_ids]
                
                # 如果还有可用物品，则随机选择一个
                if available_items:
                    return random.choice(available_items).copy()
                else:
                    # 如果所有物品都已经获得，则不再获得新物品
                    return None
            else:
                # 如果没有提供玩家背包信息，则按照原来的方式处理
                return random.choice(self.items).copy()
        return None
    
    def complete_exam(self, player, exam, base_score, item_bonus=0):
        """完成考试"""
        # 确保单科成绩不超过100分
        score = min(100, max(0, base_score + item_bonus))
        player.score += score
        
        # 记录各科成绩用于计算加权平均分
        player.exam_scores.append({
            'name': exam['name'],
            'score': score,
            'difficulty': exam['difficulty']
        })
        
        # 根据分数给出评价
        if score >= 90:
            comment = "太棒了！这门课你掌握得非常好！"
            player.health = min(100, player.health + 10)  # 高分奖励生命值
        elif score >= 75:
            comment = "干得不错，继续保持！"
        elif score >= 60:
            comment = "勉强及格，还有提升空间。"
            player.health -= 5  # 低分轻微惩罚
        else:
            comment = "考得不太理想，需要更加努力了。"
            player.health -= 15  # 低分惩罚
        
        return {
            'score': score,
            'comment': comment,
            'health_change': player.health
        }
    
    def take_quiz(self, player, exam_subject=None):
        """进行随堂测试"""
        # 根据考试科目生成相关问题
        questions_by_subject = {
            "通识选修课": [
                {
                    "question": "下列哪项不属于通识教育的目标？",
                    "options": ["培养专业技能", "拓宽知识面", "提高综合素质", "增强思辨能力"],
                    "answer": 0
                },
                {
                    "question": "通识选修课通常不包括以下哪个领域？",
                    "options": ["文学与艺术", "历史与哲学", "专业核心课程", "社会科学"],
                    "answer": 2
                }
            ],
            "体育课": [
                {
                    "question": "以下哪种运动主要以有氧代谢供能为主？",
                    "options": ["短跑", "举重", "马拉松", "跳远"],
                    "answer": 2
                },
                {
                    "question": "标准篮球场地的长度是多少米？",
                    "options": ["25米", "28米", "30米", "26米"],
                    "answer": 1
                }
            ],
            "计算机导论": [
                {
                    "question": "以下哪个不是计算机的基本组成部分？",
                    "options": ["CPU", "内存", "硬盘", "显示器"],
                    "answer": 3
                },
                {
                    "question": "二进制数1101转换为十进制是多少？",
                    "options": ["11", "12", "13", "14"],
                    "answer": 2
                }
            ],
            "大学英语": [
                {
                    "question": "下列哪个单词的复数形式是不规则变化？",
                    "options": ["cat - cats", "dog - dogs", "child - children", "book - books"],
                    "answer": 2
                },
                {
                    "question": "在英语语法中，'I have finished my homework' 是什么时态？",
                    "options": ["一般现在时", "现在进行时", "现在完成时", "一般过去时"],
                    "answer": 2
                }
            ],
            "数据结构": [
                {
                    "question": "以下哪种数据结构是先进先出（FIFO）的？",
                    "options": ["栈", "队列", "链表", "树"],
                    "answer": 1
                },
                {
                    "question": "在二叉搜索树中，左子树的所有节点值与根节点的关系是？",
                    "options": ["大于根节点", "小于根节点", "等于根节点", "无特定关系"],
                    "answer": 1
                }
            ],
            "线性代数": [
                {
                    "question": "行列式的值为0表示什么？",
                    "options": ["矩阵可逆", "矩阵不可逆", "矩阵是对称的", "矩阵是正交的"],
                    "answer": 1
                },
                {
                    "question": "n阶单位矩阵的行列式值是多少？",
                    "options": ["0", "1", "n", "n!"],
                    "answer": 1
                }
            ],
            "微积分": [
                {
                    "question": "导数的几何意义是什么？",
                    "options": ["曲线与x轴围成的面积", "曲线的切线斜率", "曲线的长度", "曲线的对称轴"],
                    "answer": 1
                },
                {
                    "question": "∫x²dx的结果是什么？",
                    "options": ["x³/3 + C", "x³ + C", "2x + C", "x²/2 + C"],
                    "answer": 0
                }
            ]
        }
        
        # 如果没有提供考试科目，则使用通用问题
        if not exam_subject or exam_subject not in questions_by_subject:
            questions = [
                {
                    "question": "下列哪个不是编程语言？",
                    "options": ["Python", "Java", "Photoshop", "C++"],
                    "answer": 2
                },
                {
                    "question": "CPU的中文全称是什么？",
                    "options": ["中央处理器", "图形处理器", "内存", "硬盘"],
                    "answer": 0
                },
                {
                    "question": "下列哪个是数据库管理系统？",
                    "options": ["MySQL", "Windows", "Linux", "Chrome"],
                    "answer": 0
                },
                {
                    "question": "HTTP协议的默认端口号是多少？",
                    "options": ["21", "25", "80", "110"],
                    "answer": 2
                },
                {
                    "question": "1GB等于多少MB？",
                    "options": ["100MB", "1000MB", "1024MB", "10000MB"],
                    "answer": 2
                }
            ]
        else:
            questions = questions_by_subject[exam_subject]
        
        # 随机选择一个问题
        question = random.choice(questions)
        return question
    
    def get_study_question(self, subject=None):
        """获取学习相关的问题"""
        # 学习问题与考试问题可以共用，但也可以添加更多基础问题
        study_questions_by_subject = {
            "通识选修课": [
                {
                    "question": "通识教育的主要目的是什么？",
                    "options": ["提高专业技能", "拓宽知识视野", "增加学分", "应付学校要求"],
                    "answer": 1
                },
                {
                    "question": "下列哪项最能体现批判性思维？",
                    "options": ["接受权威观点", "独立思考分析", "死记硬背", "从众心理"],
                    "answer": 1
                },
                {
                    "question": "通识选修课通常不包括以下哪个领域？",
                    "options": ["文学与艺术", "历史与哲学", "专业核心课程", "社会科学"],
                    "answer": 2
                },
                {
                    "question": "下列哪项不属于通识教育的目标？",
                    "options": ["培养专业技能", "拓宽知识面", "提高综合素质", "增强思辨能力"],
                    "answer": 0
                },
                {
                    "question": "通识教育有助于培养学生的哪种能力？",
                    "options": ["单一专业技能", "跨学科思维", "死记硬背能力", "应试技巧"],
                    "answer": 1
                }
            ],
            "体育课": [
                {
                    "question": "有氧运动对身体的主要好处是什么？",
                    "options": ["增加肌肉体积", "提高心肺功能", "增强爆发力", "改善柔韧性"],
                    "answer": 1
                },
                {
                    "question": "健康成年人每周应至少进行多少分钟中等强度有氧运动？",
                    "options": ["60分钟", "100分钟", "150分钟", "200分钟"],
                    "answer": 2
                },
                {
                    "question": "以下哪种运动主要以有氧代谢供能为主？",
                    "options": ["短跑", "举重", "马拉松", "跳远"],
                    "answer": 2
                },
                {
                    "question": "标准篮球场地的长度是多少米？",
                    "options": ["25米", "28米", "30米", "26米"],
                    "answer": 1
                },
                {
                    "question": "体育锻炼对心理健康的益处不包括以下哪项？",
                    "options": ["缓解压力", "改善情绪", "增强自信", "增加焦虑"],
                    "answer": 3
                }
            ],
            "计算机导论": [
                {
                    "question": "计算机中信息存储的基本单位是什么？",
                    "options": ["位(bit)", "字节(Byte)", "字(Word)", "双字"],
                    "answer": 1
                },
                {
                    "question": "操作系统的主要功能不包括以下哪项？",
                    "options": ["内存管理", "文件管理", "硬件驱动", "编写程序"],
                    "answer": 3
                },
                {
                    "question": "以下哪个不是计算机的基本组成部分？",
                    "options": ["CPU", "内存", "硬盘", "显示器"],
                    "answer": 3
                },
                {
                    "question": "二进制数1101转换为十进制是多少？",
                    "options": ["11", "12", "13", "14"],
                    "answer": 2
                },
                {
                    "question": "计算机网络的主要功能不包括以下哪项？",
                    "options": ["资源共享", "信息传输", "分布式处理", "增加硬件成本"],
                    "answer": 3
                }
            ],
            "大学英语": [
                {
                    "question": "英语学习中，哪项技能被认为是基础？",
                    "options": ["写作", "听力", "词汇", "口语"],
                    "answer": 2
                },
                {
                    "question": "下列哪种方法最有助于扩大词汇量？",
                    "options": ["死记硬背", "语境中学习", "只背拼写", "只学语法"],
                    "answer": 1
                },
                {
                    "question": "下列哪个单词的复数形式是不规则变化？",
                    "options": ["cat - cats", "dog - dogs", "child - children", "book - books"],
                    "answer": 2
                },
                {
                    "question": "在英语语法中，'I have finished my homework' 是什么时态？",
                    "options": ["一般现在时", "现在进行时", "现在完成时", "一般过去时"],
                    "answer": 2
                },
                {
                    "question": "英语写作中，主题句通常出现在段落的什么位置？",
                    "options": ["段落末尾", "段落中间", "段落开头", "任意位置"],
                    "answer": 2
                }
            ],
            "数据结构": [
                {
                    "question": "数据结构主要研究什么？",
                    "options": ["数据的存储结构", "数据的逻辑结构", "数据的操作运算", "以上都是"],
                    "answer": 3
                },
                {
                    "question": "算法分析主要关注哪两个方面？",
                    "options": ["正确性和可读性", "时间和空间复杂度", "简洁性和美观性", "速度和内存"],
                    "answer": 1
                },
                {
                    "question": "以下哪种数据结构是先进先出（FIFO）的？",
                    "options": ["栈", "队列", "链表", "树"],
                    "answer": 1
                },
                {
                    "question": "在二叉搜索树中，左子树的所有节点值与根节点的关系是？",
                    "options": ["大于根节点", "小于根节点", "等于根节点", "无特定关系"],
                    "answer": 1
                },
                {
                    "question": "下列排序算法中，平均时间复杂度为O(n log n)的是？",
                    "options": ["冒泡排序", "插入排序", "快速排序", "选择排序"],
                    "answer": 2
                }
            ],
            "线性代数": [
                {
                    "question": "矩阵乘法满足以下哪个运算律？",
                    "options": ["交换律", "结合律", "消去律", "分配律"],
                    "answer": 1
                },
                {
                    "question": "向量组线性无关的充要条件是什么？",
                    "options": ["存在零向量", "向量个数等于维数", "没有一个向量可由其余向量线性表示", "所有向量都相等"],
                    "answer": 2
                },
                {
                    "question": "行列式的值为0表示什么？",
                    "options": ["矩阵可逆", "矩阵不可逆", "矩阵是对称的", "矩阵是正交的"],
                    "answer": 1
                },
                {
                    "question": "n阶单位矩阵的行列式值是多少？",
                    "options": ["0", "1", "n", "n!"],
                    "answer": 1
                },
                {
                    "question": "线性方程组有唯一解的充要条件是什么？",
                    "options": ["系数矩阵行满秩", "系数矩阵列满秩", "系数矩阵行列式不为0", "常数项全为0"],
                    "answer": 2
                }
            ],
            "微积分": [
                {
                    "question": "函数在某点可导的必要条件是什么？",
                    "options": ["在该点连续", "在该点有定义", "在该点左右极限存在", "在该点可微"],
                    "answer": 0
                },
                {
                    "question": "定积分的几何意义是什么？",
                    "options": ["求函数的导数", "求曲线的切线斜率", "求曲边梯形的面积", "求函数的极值"],
                    "answer": 2
                },
                {
                    "question": "导数的几何意义是什么？",
                    "options": ["曲线与x轴围成的面积", "曲线的切线斜率", "曲线的长度", "曲线的对称轴"],
                    "answer": 1
                },
                {
                    "question": "∫x²dx的结果是什么？",
                    "options": ["x³/3 + C", "x³ + C", "2x + C", "x²/2 + C"],
                    "answer": 0
                },
                {
                    "question": "微积分基本定理建立了哪两个概念之间的联系？",
                    "options": ["导数与极限", "积分与极限", "导数与积分", "连续与可导"],
                    "answer": 2
                }
            ]
        }
        
        # 如果没有提供科目，则使用通用问题
        if not subject or subject not in study_questions_by_subject:
            questions = [
                {
                    "question": "有效的学习方法不包括以下哪项？",
                    "options": ["主动思考", "及时复习", "死记硬背", "举一反三"],
                    "answer": 2
                },
                {
                    "question": "学习过程中最重要的因素是什么？",
                    "options": ["学习时间", "学习方法", "学习兴趣", "以上都是"],
                    "answer": 3
                },
                {
                    "question": "以下哪种学习方式最有效？",
                    "options": ["被动接受", "主动探索", "机械记忆", "临时抱佛脚"],
                    "answer": 1
                },
                {
                    "question": "学习新知识时，以下哪种方法更有利于长期记忆？",
                    "options": ["一次性大量学习", "分散学习", "只看不练", "只练不看"],
                    "answer": 1
                },
                {
                    "question": "以下哪种复习方法更有效？",
                    "options": ["考前突击", "定期回顾", "只读不写", "只写不读"],
                    "answer": 1
                },
                {
                    "question": "下列哪项不是提高学习效率的方法？",
                    "options": ["制定学习计划", "创造良好学习环境", "一心多用", "劳逸结合"],
                    "answer": 2
                }
            ]
        else:
            questions = study_questions_by_subject[subject]
        
        # 随机选择一个问题
        question = random.choice(questions)
        return question